import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/material.dart';
import 'package:wanAndroid/common/uts/log_uts.dart';

import 'http_cookie.dart';

typedef OnSuccess = Function(Response response);
typedef OnFail = Function(Exception e);

class HttpCallback {
  OnSuccess onSuccess;
  OnFail onFail;

  HttpCallback(this.onSuccess, this.onFail);
}

class HttpUts {
  static final String GET = "get";
  static final String POST = "post";
  Dio _dio;

  HttpUts._() {
    _dio = Dio()
      ..options = BaseOptions(
        baseUrl: "https://www.wanandroid.com",
        connectTimeout: 25000,
        receiveTimeout: 30000,
      )
      ..interceptors.add(CookieManager(CookieJar()))
      ..interceptors.add(HttpCookie());
  }

  static HttpUts _httpUts = HttpUts._();

  factory HttpUts._getInstance() => _httpUts;

  ///判断是否成功
  static bool isSuccess(int errorCode) {
    return 0 == errorCode;
  }

  static void request(
    String url, {
    @required HttpCallback callback,
    Map<String, dynamic> data,
    FormData formData,
    Map<String, dynamic> headers,
    String method,
  }) async {
    HttpUts._getInstance()._request(url,
        callback: callback,
        data: data,
        headers: headers,
        method: method,
        formData: formData);
  }

  void _request(
    String url, {
    @required HttpCallback callback,
    Map<String, dynamic> data,
    FormData formData,
    Map<String, dynamic> headers,
    String method,
  }) async {
    data = data ?? {};
    headers = headers ?? {};
    method = method ??= HttpUts.GET;
    callback = callback ?? HttpCallback((response) {}, (e) {});

    /// 是否是get
    final bool isGet = method == HttpUts.GET;

    ///
    LogUts.netLog("【请求方法】== $method");
    LogUts.netLog("【请求地址】== $url");

    /// 是 get
    if (isGet) {
      //请求参数
      data.forEach((key, value) {
        if (url.indexOf("$key") != -1) {
          url = url.replaceAll(":$key", value.toString());
        }
      });

      LogUts.netLog("【请求数据】== $data");
    }

    try {
      final Response response = await _dio.request(
        url,
        options: Options(
          headers: headers,
          method: method,
        ),
        data: isGet ? null : formData,
      );

      ///
      for (var h in response.headers.map.entries) {
        LogUts.netLog("相应头 == 【${h.key}=${h.value}】");
      }
      LogUts.netLog("相应结果 == ${response.toString()}");
      callback.onSuccess(response);
    } on DioError catch (e) {
      ///
      LogUts.errorLog("$e");
      callback.onFail(e);
    }
  }
}
